package com.wyz.web;

import com.wyz.dao.UserDao2;
import com.wyz.entity.UserInfo;
import com.wyz.service.User2Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/login1")
public class LoginServlet1 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //      获取响应流，通过字符流向页面发送文本信息
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String save = req.getParameter("name");
        User2Service us = new User2Service();
        boolean flag = us.selectB2(name, pwd);
        if (flag){
//            登陆成功
            if (save.equals("checkOn")){
                Cookie cookie1 = new Cookie("username", name);
                Cookie cookie2 = new Cookie("password", pwd);
                cookie1.setMaxAge(7*24*60*60);
                cookie2.setMaxAge(7*24*60*60);
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }
//            将用户登录的信息保存到session中
            UserDao2 ud = new UserDao2();
            UserInfo userInfo = (UserInfo) ud.selectUser2(name,pwd);
            HttpSession session = req.getSession();
            session.setAttribute("userInfo", userInfo);
            req.getRequestDispatcher("studentAll").forward(req,resp);
        }else{
//            响应给页面的数据
            pw.println("用户名或密码错误，请重新<a href = 'login.jsp'>登录</a>");
        }
    }
}
